<?xml version="1.0" encoding="UTF-8" ?>
<!--

    Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
    under one or more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding copyright
    ownership. Camunda licenses this file to you under the Apache License,
    Version 2.0; you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 

<mapper namespace="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionEntity">

  <!-- CASEDEFINITION INSERT -->

  <insert id="insertCaseDefinition" parameterType="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionEntity">
    insert into ${prefix}ACT_RE_CASE_DEF(
      ID_, 
      CATEGORY_, 
      NAME_, 
      KEY_, 
      VERSION_, 
      DEPLOYMENT_ID_, 
      RESOURCE_NAME_, 
      DGRM_RESOURCE_NAME_, 
      TENANT_ID_,
      HISTORY_TTL_,
      REV_)
    values (#{id, jdbcType=VARCHAR},
            #{category, jdbcType=VARCHAR},
            #{name, jdbcType=VARCHAR},
            #{key, jdbcType=VARCHAR}, 
            #{version, jdbcType=INTEGER},
            #{deploymentId, jdbcType=VARCHAR},
            #{resourceName, jdbcType=VARCHAR},
            #{diagramResourceName, jdbcType=VARCHAR},
            #{tenantId, jdbcType=VARCHAR},
            #{historyTimeToLive, jdbcType=INTEGER},
            1
           )
  </insert>

  <!-- CASEDEFINITION UPDATE -->

  <update id="updateCaseDefinition" parameterType="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionEntity">
    update ${prefix}ACT_RE_CASE_DEF set
      REV_ = #{revisionNext, jdbcType=INTEGER},
      HISTORY_TTL_ = #{historyTimeToLive, jdbcType=INTEGER}
    where ID_ = #{id, jdbcType=VARCHAR}
      and REV_ = #{revision, jdbcType=INTEGER}
  </update>

  <!-- CASEDEFINITION DELETE -->

  <delete id="deleteCaseDefinitionsByDeploymentId" parameterType="string">
    delete from ${prefix}ACT_RE_CASE_DEF where DEPLOYMENT_ID_ = #{deploymentId} 
  </delete>

  <!-- CASEDEFINITION RESULTMAP -->

  <resultMap id="caseDefinitionResultMap" type="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionEntity">
    <id property="id" column="ID_" jdbcType="VARCHAR" />
    <result property="revision" column="REV_" />
    <result property="category" column="CATEGORY_" />
    <result property="name" column="NAME_" />
    <result property="key" column="KEY_" jdbcType="VARCHAR" />
    <result property="version" column="VERSION_" jdbcType="INTEGER"/>
    <result property="deploymentId" column="DEPLOYMENT_ID_" jdbcType="VARCHAR"/>
    <result property="resourceName" column="RESOURCE_NAME_" jdbcType="VARCHAR"/>
    <result property="diagramResourceName" column="DGRM_RESOURCE_NAME_" jdbcType="VARCHAR"/>
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR"/>
    <result property="historyTimeToLive" column="HISTORY_TTL_" jdbcType="INTEGER" /> 
  </resultMap>

  <!-- CASEDEFINITION SELECT -->

  <select id="selectCaseDefinition" parameterType="string" resultMap="caseDefinitionResultMap">
    select * from ${prefix}ACT_RE_CASE_DEF where ID_ = #{caseDefinitionId}
  </select>

  <select id="selectCaseDefinitionByDeploymentId" parameterType="string" resultMap="caseDefinitionResultMap">
    select * from ${prefix}ACT_RE_CASE_DEF where DEPLOYMENT_ID_ = #{parameter}
  </select>

  <select id="selectCaseDefinitionByDeploymentAndKey" parameterType="map" resultMap="caseDefinitionResultMap">
    select * 
    from ${prefix}ACT_RE_CASE_DEF 
    where DEPLOYMENT_ID_ = #{deploymentId}
      and KEY_ = #{caseDefinitionKey}
  </select>

  <select id="selectLatestCaseDefinitionByKey" parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject" resultMap="caseDefinitionResultMap">
    select *
    from ${prefix}ACT_RE_CASE_DEF c1
      inner join
          (select KEY_, TENANT_ID_, max(VERSION_) as MAX_VERSION
          from ${prefix}ACT_RE_CASE_DEF RES
          where KEY_ = #{parameter}
            <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheck" />
          group by TENANT_ID_, KEY_) c2
        on c1.KEY_ = c2.KEY_
    where c1.VERSION_ = c2.MAX_VERSION and 
          (c1.TENANT_ID_ = c2.TENANT_ID_ or (c1.TENANT_ID_ is null and c2.TENANT_ID_ is null))
  </select>
  
  <select id="selectLatestCaseDefinitionByKeyWithoutTenantId" parameterType="map" resultMap="caseDefinitionResultMap">
    select *
    from ${prefix}ACT_RE_CASE_DEF 
    where KEY_ = #{caseDefinitionKey}
          and TENANT_ID_ is null
          and VERSION_ = (
              select max(VERSION_) 
              from ${prefix}ACT_RE_CASE_DEF 
              where KEY_ = #{caseDefinitionKey} and TENANT_ID_ is null)
  </select>
  
  <select id="selectLatestCaseDefinitionByKeyAndTenantId" parameterType="map" resultMap="caseDefinitionResultMap">
    select *
    from ${prefix}ACT_RE_CASE_DEF RES
    where KEY_ = #{caseDefinitionKey}
          and TENANT_ID_ = #{tenantId}
          and VERSION_ = (
              select max(VERSION_) 
              from ${prefix}ACT_RE_CASE_DEF 
              where KEY_ = #{caseDefinitionKey} and TENANT_ID_ = #{tenantId})
  </select>

  <select id="selectCaseDefinitionByKeyVersionAndTenantId" parameterType="map" resultMap="caseDefinitionResultMap">
    select *
    from ${prefix}ACT_RE_CASE_DEF 
    where KEY_ = #{caseDefinitionKey}
      and VERSION_ = #{caseDefinitionVersion}
      <if test="tenantId != null">
        and TENANT_ID_ = #{tenantId}
      </if>
      <if test="tenantId == null">
        and TENANT_ID_ is null
      </if>
  </select>

  <select id="selectPreviousCaseDefinitionId" parameterType="map" resultType="string">
    select distinct RES.*
      from ${prefix}ACT_RE_CASE_DEF RES
     where RES.KEY_ = #{key}
       <if test="tenantId != null">
          AND TENANT_ID_ = #{tenantId}
        </if>
        <if test="tenantId == null">
          AND TENANT_ID_ is null
        </if>
       and RES.VERSION_ = (
        select MAX(VERSION_) 
        from ${prefix}ACT_RE_CASE_DEF 
        where KEY_ = #{key} 
          <if test="tenantId != null">
            AND TENANT_ID_ = #{tenantId}
          </if>
          <if test="tenantId == null">
            AND TENANT_ID_ is null
          </if>
          AND VERSION_ &lt; #{version})
  </select>

  <select id="selectCaseDefinitionsByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionQueryImpl" resultMap="caseDefinitionResultMap">
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    select ${distinct} RES.*
    ${limitBetween}
    <include refid="selectCaseDefinitionsByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectCaseDefinitionCountByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionQueryImpl" resultType="long">
    ${countDistinctBeforeStart} RES.ID_ ${countDistinctBeforeEnd}
    <include refid="selectCaseDefinitionsByQueryCriteriaSql"/>
    ${countDistinctAfterEnd}
  </select>

  <!-- mysql specific sql -->
  <select id="selectCaseDefinitionsByQueryCriteria_mysql" parameterType="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionQueryImpl" resultMap="caseDefinitionResultMap">
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    select ${distinct} RES.* 
    ${limitBetween}
    <include refid="selectCaseDefinitionsByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <!-- mysql specific sql -->
  <select id="selectCaseDefinitionCountByQueryCriteria_mysql" parameterType="org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionQueryImpl" resultType="long">
    ${countDistinctBeforeStart} RES.ID_ ${countDistinctBeforeEnd}
    <include refid="selectCaseDefinitionsByQueryCriteriaSql"/>
    ${countDistinctAfterEnd}
  </select>

  <sql id="selectCaseDefinitionsByQueryCriteriaSql">

    from ${prefix}ACT_RE_CASE_DEF RES
    <if test="latest">
      inner join
          (select KEY_, TENANT_ID_, max(VERSION_) as MAX_VERSION
          from ${prefix}ACT_RE_CASE_DEF
          <where>
            <if test="key != null">
              KEY_ = #{key}
            </if>
          </where>
          group by TENANT_ID_, KEY_) VER
        on RES.KEY_ = VER.KEY_
    </if>
    <where>
      <if test="id != null">
        RES.ID_ = #{id}
      </if>
      <if test="ids != null &amp;&amp; ids.length > 0">
        and RES.ID_ in
        <foreach item="item" index="index" collection="ids"
                 open="(" separator="," close=")">
          #{item}
        </foreach>
      </if>
      <if test="category != null">
        and RES.CATEGORY_ = #{category}
      </if>
      <if test="categoryLike != null">
        and RES.CATEGORY_ like #{categoryLike} ESCAPE ${escapeChar}
      </if>
      <if test="name != null">
        and RES.NAME_ = #{name}
      </if>
      <if test="nameLike != null">
        and RES.NAME_ like #{nameLike} ESCAPE ${escapeChar}
      </if>
      <if test="key != null">
        and RES.KEY_ = #{key}
      </if>
      <if test="keyLike != null">
        and RES.KEY_ like #{keyLike} ESCAPE ${escapeChar}
      </if>
      <if test="resourceName != null">
        and RES.RESOURCE_NAME_ = #{resourceName}
      </if>
      <if test="resourceNameLike != null">
        and RES.RESOURCE_NAME_ like #{resourceNameLike} ESCAPE ${escapeChar}
      </if>
      <if test="version != null">
        and RES.VERSION_ = #{version}
      </if>
      <if test="deploymentId != null">
        and RES.DEPLOYMENT_ID_ = #{deploymentId}
      </if>
      <if test="latest">
       and RES.VERSION_ = VER.MAX_VERSION and 
          (RES.TENANT_ID_ = VER.TENANT_ID_ or (RES.TENANT_ID_ is null and VER.TENANT_ID_ is null)) 
      </if>
      <if test="isTenantIdSet">
        <if test="tenantIds != null &amp;&amp; tenantIds.length > 0">
          and ( RES.TENANT_ID_ in
          <foreach item="tenantId" index="index" collection="tenantIds"
                   open="(" separator="," close=")">
            #{tenantId}
          </foreach>
          <if test="includeDefinitionsWithoutTenantId">
            or RES.TENANT_ID_ is null 
          </if>
          )
        </if>
        <if test="tenantIds == null">
          and RES.TENANT_ID_ is null
        </if>
      </if>

      <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheck" />

    </where>
  </sql>

</mapper>
